'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { QUERY_KEYS } from '@/lib/queryClient'
import { toast } from 'sonner'

// 模拟 API 函数
const mockApi = {
  // 用户数据
  fetchUser: async (id: string) => {
    return {
      id,
      name: '医疗管理员',
      role: 'admin',
      permissions: ['read', 'write', 'admin']
    }
  },

  // 医院数据
  fetchHospitals: async () => {
    return [
      { id: '1', name: '北京协和医院', address: '北京市东城区', center: [116.4074, 39.9042] },
      { id: '2', name: '上海瑞金医院', address: '上海市黄浦区', center: [121.4737, 31.2304] }
    ]
  },

  fetchHospital: async (id: string) => {
    return {
      id,
      name: '北京协和医院',
      address: '北京市东城区',
      center: [116.4074, 39.9042],
      buildings: [
        { id: 'b1', name: '门诊楼', floors: ['1F', '2F', '3F'] },
        { id: 'b2', name: '住院楼', floors: ['1F', '2F', '3F', '4F'] }
      ]
    }
  },

  // 实时数据
  fetchRealTimeData: async () => {
    return {
      timestamp: Date.now(),
      patientCount: Math.floor(Math.random() * 1000) + 500,
      equipmentStatus: {
        online: Math.floor(Math.random() * 50) + 40,
        offline: Math.floor(Math.random() * 10) + 5
      },
      alerts: Math.floor(Math.random() * 5)
    }
  },

  // 热力图数据
  fetchHeatmapData: async () => {
    const data = []
    for (let x = 0; x < 20; x++) {
      for (let y = 0; y < 15; y++) {
        data.push([x, y, Math.random() * 100])
      }
    }
    return data
  },

  // 图表数据
  fetchChartData: async (type: string) => {
    const data = []
    const now = new Date()

    for (let i = 23; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 60 * 60 * 1000)
      data.push({
        time: date.getHours() + ':00',
        value: Math.floor(Math.random() * 100)
      })
    }

    return { type, data }
  },

  // 3D 模型数据
  fetchModelData: async (modelId: string) => {
    return {
      id: modelId,
      url: `/models/${modelId}.glb`,
      metadata: {
        size: '2.5MB',
        vertices: 12500,
        materials: 8
      }
    }
  }
}

// 用户相关 hooks
export function useUser(id: string) {
  return useQuery({
    queryKey: QUERY_KEYS.USER_PROFILE(id),
    queryFn: () => mockApi.fetchUser(id),
    enabled: !!id,
  })
}

// 医院相关 hooks
export function useHospitals() {
  return useQuery({
    queryKey: QUERY_KEYS.HOSPITALS,
    queryFn: mockApi.fetchHospitals,
    staleTime: 10 * 60 * 1000, // 医院数据变化较少，缓存更久
  })
}

export function useHospital(id: string) {
  return useQuery({
    queryKey: QUERY_KEYS.HOSPITAL(id),
    queryFn: () => mockApi.fetchHospital(id),
    enabled: !!id,
  })
}

// 实时数据 hooks
export function useRealTimeData() {
  return useQuery({
    queryKey: QUERY_KEYS.REAL_TIME_DATA,
    queryFn: mockApi.fetchRealTimeData,
    refetchInterval: 5000, // 每5秒刷新
    staleTime: 0, // 实时数据不缓存
  })
}

export function useHeatmapData() {
  return useQuery({
    queryKey: QUERY_KEYS.HEATMAP_DATA,
    queryFn: mockApi.fetchHeatmapData,
    refetchInterval: 10000, // 每10秒刷新
    staleTime: 0,
  })
}

// 图表数据 hooks
export function useChartData(type: string) {
  return useQuery({
    queryKey: QUERY_KEYS.CHART_DATA(type),
    queryFn: () => mockApi.fetchChartData(type),
    staleTime: 2 * 60 * 1000, // 图表数据缓存2分钟
  })
}

// 3D 模型数据 hooks
export function useModelData(modelId: string) {
  return useQuery({
    queryKey: QUERY_KEYS.MODEL_DATA(modelId),
    queryFn: () => mockApi.fetchModelData(modelId),
    enabled: !!modelId,
    staleTime: 30 * 60 * 1000, // 模型数据缓存30分钟
  })
}

// 数据更新 mutations
export function useUpdateHospital() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (data: any) => {
      // 立即返回数据
      return data
    },
    onSuccess: (data) => {
      // 更新缓存
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.HOSPITALS })
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.HOSPITAL(data.id) })
      toast.success('医院信息更新成功')
    },
    onError: (error) => {
      toast.error('更新失败: ' + error.message)
    }
  })
}

// 预加载数据
export function usePrefetchData() {
  const queryClient = useQueryClient()

  return {
    prefetchHospitals: () => {
      queryClient.prefetchQuery({
        queryKey: QUERY_KEYS.HOSPITALS,
        queryFn: mockApi.fetchHospitals,
        staleTime: 10 * 60 * 1000,
      })
    },

    prefetchRealTimeData: () => {
      queryClient.prefetchQuery({
        queryKey: QUERY_KEYS.REAL_TIME_DATA,
        queryFn: mockApi.fetchRealTimeData,
        staleTime: 0,
      })
    },

    prefetchChartData: (type: string) => {
      queryClient.prefetchQuery({
        queryKey: QUERY_KEYS.CHART_DATA(type),
        queryFn: () => mockApi.fetchChartData(type),
        staleTime: 2 * 60 * 1000,
      })
    }
  }
}
